unit logger;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, TypInfo;


type
  TLogSubSystem = (TLSS_IO,TLSS_GUI,TLSS_Log,TLSS_AI,TLSS_SystemManager,TLSS_StateMachine,TLSS_Other);
  TLogLevel = (TLL_Critical,TLL_Error,TLL_Info);

  { TLog }
  TLog = class
    protected
      FFile: TStream;
    protected
      procedure WirteString(AStr: String);
    public
      procedure Log(AMsg: String; ASystem: TLogSubSystem=TLSS_Other; ALevel: TLogLevel=TLL_Info);
    public
      constructor Create(Path: String);
      destructor Destroy; override;
  end;

implementation

uses
  SystemManager;

{ TLog }

procedure TLog.WirteString(AStr: String);
var
  str: WideString;
  L: Integer;
begin
  str := AStr+sLineBreak;
  L := Length(str)*SizeOf(WideChar);
  FFile.WriteBuffer (Pointer(str)^,L);
end;

procedure TLog.Log(AMsg: String;  ASystem: TLogSubSystem; ALevel: TLogLevel);
begin
  WirteString(format('%s %s %s %s',[
                              FormatDateTime('dd.mm.yyyy hh:mm:ss.zzz',now),
                              GetEnumName(TypeInfo(TLogSubSystem),integer(ASystem)),
                              GetEnumName(TypeInfo(TLogLevel),integer(ALevel)),
                              AMsg
                              ]));
end;

constructor TLog.Create(Path: String);
begin
  FFile := TFileStream.Create(Path, fmCreate);
  FFile.Position := FFile.Size;
  log('Log started',TLSS_Log);
end;

destructor TLog.Destroy;
begin
  log('Log ended',TLSS_Log);
  FFile.Free;
  inherited Destroy;
end;

end.

